<?php
namespace Home\Controller;
use Think\Controller;
use Think\Model;

class IndexController extends CommonController {
    public function index(){
        //查寻轮播图
        $slideshow = M('lb_picture')->select();

        $row = 8;
        $where['is_new'] = 1;

        $list = M('goods')->where($where)->page(1,$row)->order('good_id desc')->select();

        //获取一级分类
        $cate_name = M('good_cate')->field('id,good_cate_name')->where('good_parent_id=0 OR good_parent_id=id')->select();
        //将二级分类插入到一级中
        foreach ($cate_name as $k=>$v){
            $cate_name[$k]['data'] = M('good_cate')->field('id,good_cate_name,cate_picture')->where('good_parent_id='.$v['id'])->select();
        }

        $this->assign('cate_name',$cate_name);
        $this->assign('list',$list);
        $this->assign('slideshow',$slideshow);
        $this->display();
    }

    //AJAX瀑布流获取商品
    public function upData(){
        $row = 8;
        $page = I('page');
        $cate_id = I('cate_id');//值为空是新品的列表页，否则是分类商品的列表页
        //上拉加载新品
        if($cate_id == '')
        {
            $where['is_new'] = 1;
        }else{
            $where['cate_id'] = $cate_id;
        }
        $list = M('goods')->where($where)->page($page,$row)->order('good_id desc')->select();
        if($list){
            echo json_encode($list);
        }else{
            echo -1;
        }
    }

    //分类商品列表
    public function shop_cate_goods(){
        $cate_id = I('cate_id');
        $search = I('search');
        $row = 8;
        $where = '';
        //如果存在分类ID,展示当前分类商品，没有的话，查看是否存在搜索条件，没有的话，默认展示第一个分类下的商品
        if($cate_id != '')
        {
            $where['cate_id'] = $cate_id;
        }else{
            if($search != '')
            {
                $where['good_name'] = array('like',"%$search%");
            }else{
                //默认展示分类列表第一个分类下的商品，促销产品
                $where['cate_id'] = 1;
            }
        }


        $list = M('goods')->where($where)->page(1,$row)->order('good_id desc')->select();

        //获取一级分类
        $cate_name = M('good_cate')->field('id,good_cate_name')->where('good_parent_id=0 OR good_parent_id=id')->select();
        //将二级分类插入到一级中
        foreach ($cate_name as $k=>$v){
            $cate_name[$k]['data'] = M('good_cate')->field('id,good_cate_name,cate_picture')->where('good_parent_id='.$v['id'])->select();
        }

        //如果存在分类ID,查询对应的分类名称
        if($where['cate_id'] != '')
        {
            $cateInfo = M('good_cate')->field('good_cate_name')->where(array('id' => $where['cate_id']))->find();
            $this->assign('cate_id',$where['cate_id']);
            $this->assign('good_cate_name',$cateInfo['good_cate_name']);
        }

        $this->assign('cate_name',$cate_name);
        $this->assign('list',$list);
        $this->assign('search',$search);
        $this->display();
    }

    //商品详情
    public function shop_details(){
        $id = I('id');
        $info = M('goods')->where('good_id='.$id)->find();
        //将商品辅图转为数组
        $info['assist_picture'] = json_decode($info['assist_picture'],true);
        
        $this->assign('info',$info);

        //获取一级分类
        $cate_name = M('good_cate')->field('id,good_cate_name')->where('good_parent_id=0 OR good_parent_id=id')->select();
        //将二级分类插入到一级中
        foreach ($cate_name as $k=>$v){
            $cate_name[$k]['data'] = M('good_cate')->field('id,good_cate_name')->where('good_parent_id!=id and good_parent_id='.$v['id'])->select();
        }

        $this->assign('cate_name',$cate_name);
        $this->display();
    }

    //加入购物车
    public function add_cart(){
        $data['user_id'] = session('user_id');
        $data['goods_id'] = I('goods_id');
        $data['goods_num'] = I('num') ? I('num') : 1;
        $data['add_time'] = date('Y-m-d H:i:s',time());
        //判断该商品是否已经加入购物车
        $where = array(
            'user_id'=>session('user_id'),
            'goods_id'=>I('goods_id')
        );
        $res = M('goods_cart')->where($where)->find();
        if($res){
            echo -1;   //表示已经加入
        }else{
            if(M('goods_cart')->add($data)){
                echo 1;
            }else{
                echo -2;
            }
        }

    }

    //购物车
    public function shop_cart(){
        //获取该用户购物车中商品
        if(session('user_id') != null){
            //获取购物车列表
            $cart_list = M('goods_cart gc')->field('gs.good_id,gs.good_name,gs.price,gs.vip_price,gs.grade,gs.picture,gc.goods_num,gc.cart_id')
                ->join('__GOODS__ gs on gs.good_id=gc.goods_id')
                ->where('user_id='.session('user_id'))
                ->order('cart_id desc')
                ->select();
        }

        $shop_cart = 'jumpPage';
        $this->assign('shop_cart',$shop_cart);
        $this->assign('list',$cart_list);
        $this->display();
    }

    //修改购物车数量
    public function cart_save(){
        $type = I('type');
        $sum = I('sum');
        $where = array(
            'cart_id'=>I('cart_id')
        );
        if($type == 'jia'){
            M('goods_cart')->where($where)->setInc('goods_num');
        }
        if($type == 'jian'){
            M('goods_cart')->where($where)->setDec('goods_num');
        }
        if($type == 'edit'){
            M('goods_cart')->where($where)->save(array('goods_num' => $sum));
        }
    }

    //退出登录
    public function login_out(){
        session('user_id',null);
        session('user_name',null);
        session('user_vip',null);
        session('user_type',null);
        session('user_real_name',null);
        $this->redirect('index');
    }

    //普通用户注册
    public function zhuce(){
        if(IS_AJAX){
            //验证手机验证码
            $time = date("Y-m-d H:i:s", time() - 600);//十分钟之内有效
            $condition = array(
                'telephone' => I('phone'),
                "code" => I('code'),
                "sendtime" => array("GT", $time)
            );
            if(!M('verify')->where($condition)->count()){
                echo -1; //验证码错误
            }else{
                $data['username'] = I('username');
                $data['phone'] = I('phone');
                $data['password'] = md5(I('password'));
                $data['add_time'] = date('Y-m-d H:i:s');
                if(M('user')->add($data)){
                    echo 1;    //成功
                }else{
                    echo -2;  //数据异常
                }
            }
            exit;
        }
        $this->display();
    }

    //验证用户名是否已注册
    public function checkUsername(){
        $where = array(
            'username'=>I('username')
        );
        if(M('user')->field('id')->where($where)->find()){
            echo -1;  //已注册
        }else{
            echo 1;
        }
    }

    //验证手机号是否已注册
    public function checkPhone(){
        $where = array(
            'phone'=>I('phone')
        );
        if(M('user')->field('id')->where($where)->find()){
            echo -1;  //已注册
        }else{
            echo 1;
        }
    }

    //电工注册
    public function yuangongziliao(){
        if(!IS_POST){
            //获取所有省份
            $province_list = M('area')->where(array('parentId' => 0))->select();
            //获取电工服务协议条款
            $electrician_agreement = M('electrician_agreement')->where(array('id'=>1))->getField('electrician_agreement');

            $this->assign('electrician_agreement',$electrician_agreement);
            $this->assign('province_list',$province_list);
            $this->display();
        }else{
            $picture = upload();
            $data['electrician_id'] = session('user_id');
            $data['real_name'] = I('real_name');
            $data['id_number'] = I('id_number');
            $data['province'] = I('province');
            $data['city'] = I('city');
            $data['county'] = I('county');
            $data['town'] = I('town');
            $data['identity_card_front'] = $picture['identity_front'];
            $data['identity_card_reverse'] = $picture['identity_reverse'];
            $data['electrician_license_front'] = $picture['electrician_front'];
            $data['electrician_license_reverse'] = $picture['electrician_reverse'];
            $data['add_time'] = date('Y-m-d H:i:s');
            if(!M('electrician')->add($data)){
                $this->error('申请失败');
            }else{
                session('user_real_name',$data['real_name']);
                $this->success('申请成功',U('electrical_data'));
            }
        }
    }

    //验证身份证号是否存在
    public function id_number_exist(){
        if(M('electrician')->where(array('id_number'=>I('id_number')))->getField('id')){
            echo 1;//存在
        }else{
            echo 0;//不存在
        }
    }

    //个人中心 -- 基本资料
    public function basic_information(){
        $basic_information = 'jumpPage';
        $this->assign('basic_information',$basic_information);
        if(!IS_POST){
            $info = M('user')->where(array('id'=>session('user_id')))->find();
            $submenu = '基本资料';
            $this->assign('info',$info);
            $this->assign('submenu',$submenu);
            $this->display();
        }else{
            $data['username'] = I('username');
            $data['head_picture'] = uploadPicture();
            $data['sex'] = I('sex');
            $data['fixed_telephone'] = I('fixed_telephone');
            $data['email'] = I('email');
            $data['qq'] = I('qq');
            $data['wechat'] = I('wechat');
            if(M('user')->where(array('id'=>session('user_id')))->save($data) === false){
                $this->error('保存失败');
            }else{
                $this->success('保存成功');
            }
        }
    }

    //个人中心 -- 电工资料
    public function electrical_data(){
        $electrician_info = M('electrician as e')
            ->field('e.*,pr.name as province_name,ci.name as city_name,co.name as county_name,tw.name as town_name')
            ->join('JOIN __AREA__ pr ON pr.code = e.province')
            ->join('JOIN __AREA__ ci ON ci.code = e.city')
            ->join('JOIN __AREA__ co ON co.code = e.county')
            ->join('JOIN __AREA__ tw ON tw.code = e.town')
            ->where(array('electrician_id'=>session('user_id')))
            ->find();
        $submenu = '电工资料';
        $this->assign('electrician_info',$electrician_info);
        $this->assign('submenu',$submenu);
        $this->display();
    }

    //修改电工资料
    public function electrician_data_edit(){
        $electrician_data = M('electrician')->where(array('electrician_id'=>session('user_id')))->find();
        if(!IS_POST){
            //获取所有省份
            $province_list = M('area')->where(array('parentId' => 0))->select();
            $this->assign('province_list',$province_list);
            $this->assign('electrician_data',$electrician_data);
            $this->display();
        }else{
            $picture = upload();
            $data['real_name'] = I('real_name');
            $data['id_number'] = I('id_number');
            $data['identity_card_front'] = $picture['identity_front'];
            $data['identity_card_reverse'] = $picture['identity_reverse'];
            $data['electrician_license_front'] = $picture['electrician_front'];
            $data['electrician_license_reverse'] = $picture['electrician_reverse'];
            $data['check_status'] = 0;
            if(false === M('electrician')->where(array('electrician_id'=>session('user_id')))->save($data)){
                $this->error('修改失败');
            }else{
                session('user_real_name',$data['real_name']);
                //删除已经上传的图片
                unlink(ltrim($electrician_data['identity_card_front'],'/'));
                unlink(ltrim($electrician_data['identity_card_reverse'],'/'));
                unlink(ltrim($electrician_data['electrician_license_front'],'/'));
                unlink(ltrim($electrician_data['electrician_license_reverse'],'/'));
                $this->success('修改成功',U('electrical_data'));
            }
        }
    }
    
    //登录
    public function logining(){
        //判断验证码
        $verify =new \Think\Verify ();
        if (!$verify->check(I('verify'))) {
            echo -1; //验证码不正确
            exit;
        }
        //判断手机号和密码
        $type = I('usertype');
        $where = array(
            'phone' => I('phone'),
            'password' => md5(I('password')),
        );
        if($type == 'user'){  //用户登录
            $info = M('user')->field('id,username,vip,user_type,disabled')->where($where)->find();
            if($info){
                //判断其是否被禁用
                if($info['disabled'] == 0){
                    echo 3;
                    exit;
                }

                session('user_id',$info['id']);
                session('user_name',$info['username']);
                session('user_vip',$info['vip']);
                session('user_type',$info['user_type']);
                //判断电工资料是否已经提交
                $real_name = M('electrician')->where(array('electrician_id'=>$info['id']))->getField('real_name');
                if($real_name){
                    session('user_real_name',$real_name);
                }
                echo 1;
            }else{
                echo -2;
            }
        }else{
            $this->error('非法操作');
        }
    }

    //供货商登录
    public function dealer_logining(){
        //判断手机号和密码
        $type = I('usertype');
        $where = array(
            'phone' => I('phone'),
            'password' => md5(I('password')),
            'user_type' => 3
        );
        if($type == 'user'){  //用户登录
            $info = M('user')->field('id,username,vip,user_type,disabled')->where($where)->find();
            if($info){
                //判断其是否被禁用
                if($info['disabled'] == 0){
                    echo 3;
                    exit;
                }

                session('user_id',$info['id']);
                session('user_name',$info['username']);
                session('user_vip',1);
                session('user_type',3);

                echo 1;
            }else{
                echo -2;
            }
        }else{
            $this->error('非法操作');
        }
    }

    //找回密码验证
    public function checkZhaohui(){
        //验证手机号是否已经注册
        $where = array(
            'phone'=>I('phone')
        );
        if(!M('user')->field('id')->where($where)->find()){
            echo -2;  //未注册
        }else{
            //验证手机验证码
            $time = date("Y-m-d H:i:s", time() - 600);//十分钟之内有效
            $condition = array(
                'telephone' => I('phone'),
                "code" => I('code'),
                "sendtime" => array("GT", $time)
            );
            if(!M('verify')->where($condition)->count()){
                echo -1; //验证码错误
            }else{
                echo 1;
            }
        }
    }
    //重置密码
    public function repwd(){
        $data['password'] = md5(I('password'));
        if(M('user')->where('phone='.I('phone'))->save($data)){
            echo 1;
        }else{
            echo -1;
        }
    }

    //验证码
    public function verify()
    {
        $verify = new \Think\Verify (array(
            'fontSize' => 18,
            'imageH' => 36,
            'imageW' => 135,
            'length' => 3,
            'useCurve' => false,
            'useNoise'=>false
        ));
        $verify->entry();
    }

    //购物车删除
    public function cart_del(){
        $cart_id = I('cart_id');
        if(M('goods_cart')->where('cart_id='.$cart_id)->delete()){
            echo 1;  //删除成功
        }
    }

    //提交订单
    public function confirmOrder(){
        //接受购物车商品ID和修改后的购买数量ID，进行修改
        $cid = trim(I('cid'),',');
        $sumid = trim(I('sumid'),',');
        $cid_arr = explode(',',$cid);
        $sumid_arr = explode(',',$sumid);
        foreach($cid_arr AS $key => $val){
            M('goods_cart')->where(array('cart_id' => $val))->save(array('goods_num' => $sumid_arr[$key]));
        }

        //查询系统配置信息.获取最低安装费，安装费返点临界值，安装费返点
        $configInfo = M('system_config')->where(array('config_id' => array('in','1,2')))->getField('config_name,config_value');

        $count = 0;
        //如果$cid不为空，证明是从购物车过来的商品
        if($cid != '')
        {
            $where = array(
                'cart_id'=>array('in',$cid)
            );
            //获取购物车提交的商品
            $list = M('goods_cart gc')->field('g.*,gc.goods_num')
                ->join('__GOODS__ g on g.good_id=gc.goods_id')
                ->where($where)->select();
            $small_total = '';//普通用户小型部件总金额
            $vip_small_total = '';//vip用户小型部件总金额
            $small_install_price = '';//小型部件安装费
            $all_total = '';//除小型部件之外的总金额--普通用户
            $vip_all_total = '';//除小型部件之外的总金额--vip用户
            foreach ($list as $k=>$v){
                //获取小型部件总额和除小型部件之外的总金额和小型部件的安装费,如果为会员按会员价计算，否则按市场价计算
                if($v['alone_install'] == 1)
                {
                    //代表为小型部件，算出其总金额和安装费
                    $small_total += $v['price'];
                    $vip_small_total += $v['vip_price'];
                    $small_install_price += $v['goods_num']*$v['alone_install_price'];
                    $list[$k]['install_price'] = $v['goods_num']*$v['alone_install_price'];//单件商品安装费(小型部件)
                }else{
                    $all_total += $v['price']*$v['goods_num'];
                    $vip_all_total += $v['vip_price']*$v['goods_num'];
                    if(session('user_vip') == 1){
                        $list[$k]['install_price'] = $v['vip_price']*$v['goods_num']*$configInfo['install_price_rebate'];//单件商品安装费（除小型部件外的商品）
                    }else{
                        $list[$k]['install_price'] = $v['price']*$v['goods_num']*$configInfo['install_price_rebate'];//单件商品安装费（除小型部件外的商品）
                    }
                }
                if(session('user_vip') == 1){
                    $count += $v['vip_price']*$v['goods_num'];
                }else{
                    $count += $v['price']*$v['goods_num'];
                }

            }
            //获取总安装费
            $install_price = floor($all_total*0.1)+$small_install_price;//普通用户总安装费
            $vip_install_price = floor($vip_all_total*0.1)+$small_install_price;//vip用户总安装费
        }

        //查看用户是否存在收货地址，没有的话，直接弹出增加地址的遮罩层
        $addressList = M('area as pr')
            ->field('ua.*,pr.name as province_name,ci.name as city_name,co.name as county_name,tw.name as town_name,u.username')
            ->join('JOIN __USER_ADDRESS__ ua ON pr.code = ua.province')
            ->join('JOIN __AREA__ ci ON ci.code = ua.city')
            ->join('JOIN __AREA__ co ON co.code = ua.county')
            ->join('JOIN __AREA__ tw ON tw.code = ua.town')
            ->join('JOIN __USER__ u ON u.id = ua.user_id')
            ->where(array('user_id' => session('user_id')))
            ->select();
        //获取所有省份
        $province_list = M('area')->where(array('parentId' => 0))->select();

        //查询默认收货地址
        $default_address = M('area as pr')
            ->field('ua.*,pr.name as province_name,ci.name as city_name,co.code as county_code,co.name as county_name,tw.name as town_name,u.username')
            ->join('JOIN __USER_ADDRESS__ ua ON pr.code = ua.province')
            ->join('JOIN __AREA__ ci ON ci.code = ua.city')
            ->join('JOIN __AREA__ co ON co.code = ua.county')
            ->join('JOIN __AREA__ tw ON tw.code = ua.town')
            ->join('JOIN __USER__ u ON u.id = ua.user_id')
            ->where(array('status' => 1,'user_id' => session('user_id')))
            ->find();

        //根据默认收货地址的县或者市，查询对应的乡镇
        $town_list = M('area')->field('code,name')->where(array('parentId'=>$default_address['county_code']))->select();

        $this->assign('count',$count);
        $this->assign('install_price',$install_price);
        $this->assign('vip_install_price',$vip_install_price);
        $this->assign('cid',$cid);
        $this->assign('list',$list);
        $this->assign('addressList',$addressList);
        $this->assign('town_list',$town_list);
        $this->assign('province_list',$province_list);
        $this->assign('default_address',$default_address);
        $this->display();
    }

    //AJAX获取乡镇电工列表
    public function town_electrician_list(){
        
        $electrician_list = M('electrician as e')
            ->field('e.electrician_id,e.real_name,u.phone,t.name as town_name')
            ->join('JOIN __AREA__ t ON t.code = e.town')
            ->join('JOIN __USER__ u ON u.id = e.electrician_id')
            ->where(array('e.town'=>I('town')))
            ->select();
        echo json_encode($electrician_list);
    }

    //订单的去支付
    public function to_pay_for(){
        //接收订单编号
        $order_number = I('on');

        //查询该订单商品的信息
        $list = M('order')->where(array('order_number' => $order_number))->select();

        //获取商品总金额
        $count = M('count_price')->where(array('order_number' => $order_number))->getField('count_price');

        //获取所有省份
        $province_list = M('area')->where(array('parentId' => 0))->select();

        //查询默认收货地址
        $default_address = M('area as pr')
            ->field('ua.*,pr.name as province_name,ci.name as city_name,co.code as county_code,co.name as county_name,tw.name as town_name,u.username')
            ->join('JOIN __USER_ADDRESS__ ua ON pr.code = ua.province')
            ->join('JOIN __AREA__ ci ON ci.code = ua.city')
            ->join('JOIN __AREA__ co ON co.code = ua.county')
            ->join('JOIN __AREA__ tw ON tw.code = ua.town')
            ->join('JOIN __USER__ u ON u.id = ua.user_id')
            ->where(array('status' => 1,'user_id' => session('user_id')))
            ->find();

        $this->assign('order_number',$order_number);
        $this->assign('list',$list);
        $this->assign('count',$count);
        $this->assign('default_address',$default_address);
        $this->assign('province_list',$province_list);
        $this->display();
    }

    //AJAX -- 根据所选省份，获取所有市
    public function city()
    {
        $city_list = M('area')->field('code,name')->where(array('parentId' => I('province')))->select();
        echo json_encode($city_list);
    }

    //AJAX -- 根据所选城市，获取所有县区
    public function county()
    {
        $county_list = M('area')->field('code,name')->where(array('parentId' => I('city')))->select();
        echo json_encode($county_list);
    }

    //AJAX -- 根据所选县区，获取所有乡镇
    public function town()
    {
        $county_list = M('area')->field('code,name')->where(array('parentId' => I('county')))->select();
        echo json_encode($county_list);
    }

    //AJAX -- 经销商根据所选省份，获取所有市
    public function citys()
    {
        $city_list = M('region')->field('id,name')->where(array('pid' => I('province')))->select();
        echo json_encode($city_list);
    }

    //新增的收货地址
    public function add_edit_address()
    {
        //如果隐藏域没有待修改的为添加，否则为修改
        if(I('address_id') == '')
        {
            $data = array(
                'province' => I('province'),
                'city' => I('city'),
                'county' => I('county'),
                'town' => I('town'),
                'user_id' => session('user_id'),
                'detailed_address' => I('detailed_address'),
                'receiver' => I('receiver'),
                'postcode' => I('postcode'),
                'phone' => I('phone'),
                'fax' => I('fax'),
                'type' => I('type'),//隐藏域传值
            );

            //如果没有收货地址，设置为默认地址
            $result = M('user_address')->where(array('user_id' => session('user_id')))->find();
            if($result)
            {
                $data['status'] = 0;
            }else{
                $data['status'] = 1;
            }

            if(M('user_address')->add($data))
            {
                $this->success('保存成功');
            }else{
                $this->error('保存失败');
            }
        }else{
            $data = array(
                'address_id' => I('address_id'),
                'province' => I('province'),
                'city' => I('city'),
                'county' => I('county'),
                'town' => I('town'),
                'detailed_address' => I('detailed_address'),
                'receiver' => I('receiver'),
                'postcode' => I('postcode'),
                'phone' => I('phone'),
                'fax' => I('fax'),
            );

            if(M('user_address')->save($data) !== false)
            {
                $this->success('保存成功');
            }else{
                $this->error('保存失败');
            }
        }
    }

    //AJAX -- 删除收货地址
    public function del_address()
    {
        $del_result = M('user_address')->where(array('address_id' => I('address_id')))->delete();
        if($del_result !== false)
        {
            echo 1;//删除成功
        }else{
            echo 0;//删除失败
        }
    }

    //AJAX -- 点击选择地址，修改为默认地址
    public function save_default_address()
    {
        //将所有的地址改为非默认，获取选中地址的address_id,将其修改为默认地址
        if(M('user_address')->where(array('user_id' => session('user_id')))->save(array('status' => 0)))
        {
            $editResult = M('user_address')->where(array('address_id' => I('address_id')))->save(array('status' => 1));
            if($editResult !== false)
            {
                echo 1;
            }
        }
    }

    //AJAX -- 查询默认收货地址信息（修改时展示）
    public function address_info()
    {
        $address_info = M('user_address')->where(array('address_id' => I('address_id')))->find();
        if($address_info)
        {
            echo json_encode($address_info);
        }
    }

    //我的订单
    public function shop_order(){
        //将电工未同意的就近安装过期订单改为默认抢单
        $time = strtotime("-24 hours");
        $back_time =  date("Y-m-d H:i:s",$time);
        $condition = array(
            'user_id'=>session('user_id'),
            'install_type'=>2,
            'electrician_confirm'=>array(
                'neq',1
            ),
            'add_time'=>array(
                'lt',$back_time
            )
        );
        $data['install_type'] = 1;
        $data['electrician_confirm'] = '';
        $data['electrician_id'] = 0;
        M('order')->where($condition)->save($data);

        //执行查询
        $order_status = I('order_status');
        $where = array(
            'o.user_id'=>session('user_id'),
            'order_status'=>array('not in','-2') //去除已删除的订单
        );

        if($order_status != ''){
            $where['order_status']=$order_status;
            $this->assign('order_status',$order_status);
        }

        $row = 5;
        $p = $_GET['p'] ? $_GET['p'] : 1;
        //先按订单编号去重查询有多少订单
        $order_number_count = M('order o')
            ->field('o.*,cp.order_price,cp.count_price,cp.tracking_number,u.username,e.username AS electrician_name,e.phone as electrician_phone,
            ua.*,pr.name AS province,ci.name AS city,co.name AS county,tw.name AS town')
            ->join('__COUNT_PRICE__ cp on cp.order_number = o.order_number')
            ->join('__USER__ u on u.id = o.user_id')
            ->join('LEFT JOIN __USER__ e on e.id = o.electrician_id')
            ->join('JOIN __USER_ADDRESS__ AS ua ON o.address_id = ua.address_id')
            ->join('JOIN __AREA__ pr ON pr.code = ua.province')
            ->join('JOIN __AREA__ ci ON ci.code = ua.city')
            ->join('JOIN __AREA__ co ON co.code = ua.county')
            ->join('JOIN __AREA__ tw ON tw.code = ua.town')
            ->where($where)
            ->count("distinct o.order_number");
        $Page = new \Think\Page($order_number_count,$row);
        $show = $Page->show();
        //获取该用户的有哪些订单（订单编号去重查询）
        $order_number_list = M('order o')
            ->field('o.*,cp.order_price,cp.count_price,cp.tracking_number,u.username,e.username AS electrician_name,e.phone as electrician_phone,
            ua.*,pr.name AS province,ci.name AS city,co.name AS county,tw.name AS town')
            ->join('LEFT JOIN __COUNT_PRICE__ cp on cp.order_number = o.order_number')
            ->join('__USER__ u on u.id = o.user_id')
            ->join('LEFT JOIN __USER__ e on e.id = o.electrician_id')
            ->join('JOIN __USER_ADDRESS__ AS ua ON o.address_id = ua.address_id')
            ->join('JOIN __AREA__ pr ON pr.code = ua.province')
            ->join('JOIN __AREA__ ci ON ci.code = ua.city')
            ->join('JOIN __AREA__ co ON co.code = ua.county')
            ->join('JOIN __AREA__ tw ON tw.code = ua.town')
            ->where($where)->page($p,$row)->order('order_id desc')->group('o.order_number')->select();

        //查询系统配置信息.获取最低安装费，安装费返点临界值，安装费返点
        $configInfo = M('system_config')->where(array('config_id' => array('in','1,2')))->getField('config_name,config_value');

        //获取每个订单编号下的商品信息和商品数量
        foreach($order_number_list AS $k => $v){
            $total_freight = '';//总运费
            $good_total = '';//商品小计
            $total_install_price = '';//总安装费
            $where = array(
                'order_number' => $v['order_number'],
                'order_status' => array(
                    'not in','-2'
                ),
            );
            //商品数量
            $order_good_count = M('order')->where($where)->count();

            //对应商品
            $order_good_list = M('order')->where($where)->order('order_id desc')->select();

            //遍历商品信息获取总运费，总安装费、总额
            foreach($order_good_list AS $key => $val){
                $order_good_list[$key]['good_small_total'] = $val['price']*$val['num'];
                $total_freight += $val['freight'];
                $total_install_price += $val['install_price'];
                $good_total += $val['price']*$val['num'];
            }
            
            $order_number_list[$k]['order_good_count'] = $order_good_count;
            $order_number_list[$k]['order_good_list'] = $order_good_list;
            $order_number_list[$k]['total_freight'] = $total_freight;
            //判断总的安装费是否满足最低安装费，不满则按最低安装费计算
            if($total_install_price < $configInfo['min_install_price'] && $total_install_price != 0){
                $total_install_price = $configInfo['min_install_price'];
                $order_number_list[$k]['total_install_price'] = $configInfo['min_install_price'];
            }else{
                $order_number_list[$k]['total_install_price'] = $total_install_price;
            }
            $order_number_list[$k]['total_install_price'] = $total_install_price;
            $order_number_list[$k]['good_total'] =  $good_total;//订单小计
        }

        //导航栏选中状态
        $shop_order = 'jumpPage';
        $this->assign('shop_order',$shop_order);
        $this->assign('order_status',$order_status);
        $this->assign('order_number_list',$order_number_list);
        $this->assign('page',$show);
        $this->assign('p',$p);
        $this->display();
    }

    //取消订单
    public function order_cancel(){
        $order_status = I('order_status');
        $p = I('p');
        $on = I('on');
        $data['order_status'] = -1;
        if(false == M('order')->where('order_number='.$on)->save($data)){
            $this->error('数据异常，请稍后重试',U('shop_order',array('p'=>$p,'order_status'=>$order_status)));
        }
        $this->success('订单已取消');
    }

    //删除订单
    public function order_del(){
        $order_status = I('order_status');
        $p = I('p');
        $oc = I('oc');
        $on = I('on');
        $data['order_status'] = -2;
        //如果接受订单编号，删除所有此订单编号的订单，否则删除接受的订单ID的订单
        if($on != ''){
            if(false === M('order')->where('order_number='.$on)->save($data)){
                $this->error('数据异常，请稍后重试',U('shop_order',array('p'=>$p,'order_status'=>$order_status)));
            }
        }else{
            if(false === M('order')->where('order_id='.$oc)->save($data)){
                $this->error('数据异常，请稍后重试',U('shop_order',array('p'=>$p,'order_status'=>$order_status)));
            }
        }

        $this->success('订单已删除',U('shop_order',array('p'=>$p,'order_status'=>$order_status)));
    }

    //确认收货
    public function order_succ(){
        $order_status = I('order_status');
        $p = I('p');
        $on = I('on');
        $data['order_status']=3;
        $data['confirm_time']=date('Y-m-d H:i:s');
        if(false === M('order')->where('order_number='.$on)->save($data)){
            $this->error('数据异常，请稍后重试',U('shop_order',array('p'=>$p,'order_status'=>$order_status)));
        }
        $this->success('收货成功',U('shop_order',array('p'=>$p,'order_status'=>$order_status)));
    }

    //申请退换货
    public function shop_tuihuo(){
        if(!IS_POST)
        {
            $order_status = I('order_status');
            $p = I('p');
            $id = I('oc');
            $where['order_id'] = $id;

            //查询退换货订单信息
            $orderInfo = M('order')
                ->field('o.*,ua.*,pr.name AS province,ci.name AS city,co.name AS county,tw.name AS town')
                ->join('AS o JOIN __USER_ADDRESS__ AS ua ON o.address_id = ua.address_id')
                ->join('JOIN __AREA__ pr ON pr.code = ua.province')
                ->join('JOIN __AREA__ ci ON ci.code = ua.city')
                ->join('JOIN __AREA__ co ON co.code = ua.county')
                ->join('JOIN __AREA__ tw ON tw.code = ua.town')
                ->where($where)
                ->find();
            $this->assign('p',$p);
            $this->assign('order_status',$order_status);
            $this->assign('orderInfo',$orderInfo);
            $this->display();
            exit;
        }else{
            $order_status = I('order_status');
            $p = I('p');
            $picture = json_encode(upload());
            $data['order_id'] = I('order_id');
            $data['order_status'] = 4;
            $data['apply_return_time'] = date('Y-m-d H:i:s');
            $data['return_num'] = I('return_num');
            $data['return_reason'] = I('return_reason');
            $data['return_picture'] = $picture;
            M('order')->save($data);
            if(false === M('order')->save($data)){
                $this->error('数据异常，请稍后重试',U('shop_order',array('p'=>$p,'order_status'=>$order_status)));
            }
            $this->success('提交成功',U('shop_order',array('p'=>$p,'order_status'=>$order_status)));
        }

    }

    //查看换货信息和用户的点击已换货
    public function order_return_info()
    {
        if(!IS_POST)
        {
            $order_status = I('order_status');
            $p = I('p');
            $id = I('oc');
            $where['order_id'] = $id;
            //查询退换货订单信息
            $orderInfo = M('order')
                ->field('o.*,ua.*,pr.name AS province,ci.name AS city,co.name AS county,tw.name AS town')
                ->join('AS o JOIN __USER_ADDRESS__ AS ua ON o.address_id = ua.address_id')
                ->join('JOIN __AREA__ pr ON pr.code = ua.province')
                ->join('JOIN __AREA__ ci ON ci.code = ua.city')
                ->join('JOIN __AREA__ co ON co.code = ua.county')
                ->join('JOIN __AREA__ tw ON tw.code = ua.town')
                ->where($where)
                ->find();
            //将订单中换货由JSON格式转化为数组
            $orderInfo['return_picture'] = json_decode($orderInfo['return_picture'],true);
            $this->assign('orderInfo',$orderInfo);
            $this->assign('p',$p);
            $this->assign('order_status',$order_status);
            $this->display();
            exit;
        }else{
            $order_status = I('order_status');
            $p = I('p');
            $data['order_id'] = I('order_id');
            $data['order_status'] = 6;
            $data['return_time'] = date('Y-m-d H:i:s');
            M('order')->save($data);
            if(false === M('order')->save($data)){
                $this->error('数据异常，请稍后重试',U('shop_order',array('p'=>$p,'order_status'=>$order_status)));
            }
            $this->success('提交成功',U('shop_order',array('p'=>$p,'order_status'=>$order_status)));
        }
    }
    
    //已换货
    public function order_barter(){
        $order_status = I('order_status');
        $p = I('p');
        $id = I('oc');
        $data['order_status']=6;
        if(false == M('order')->where('order_id='.$id)->save($data)){
            $this->error('数据异常，请稍后重试',U('shop_order',array('p'=>$p,'order_status'=>$order_status)));
        }
        $this->success('操作成功',U('shop_order',array('p'=>$p,'order_status'=>$order_status)));
    }

    //已退货
    public function order_refund(){
        $id = I('oc');
        $data['order_status']=9;
        if(false == M('order')->where('order_id='.$id)->save($data)){
            $this->error('数据异常，请稍后重试');
        }
        $this->success('操作成功');
    }

    //修改密码：验证手机号及密码
    public function check(){
        $where = array(
            'phone'=>I('phone'),
            'password'=>md5(I('password'))
        );
        if(M('user')->where($where)->find()){
            echo 1;   //验证正确
        }else{  
            echo -1;  //手机号或密码错误
        }
    }
    //修改密码：修改
    public function updatePwd(){
        $data['password'] = md5(I('password'));
        if(false == M('user')->where('phone='.I('phone'))->save($data)){
            echo -1;
        }else{
            echo 1;   //修改成功
        }
    }

    //抢单列表
    public function shop_qiang(){
        //获取一级分类
        $cate_name = M('good_cate')->field('id,good_cate_name')->where('good_parent_id=0 OR good_parent_id=id')->select();
        //将二级分类插入到一级中
        foreach ($cate_name as $k=>$v){
            $cate_name[$k]['data'] = M('good_cate')->field('id,good_cate_name')->where('good_parent_id!=id and good_parent_id='.$v['id'])->select();
        }

        //将电工未同意的就近安装过期订单改为默认抢单
        $time = strtotime("-24 hours");
        $back_time =  date("Y-m-d H:i:s",$time);
        $condition = array(
            'install_type'=>2,
            'electrician_confirm'=>array(
                'neq',1
            ),
            'pay_time'=>array(
                'lt',$back_time
            )
        );
        $data['install_type'] = 1;
        $data['electrician_confirm'] = '';
        $data['electrician_id'] = 0;
        M('order')->where($condition)->save($data);

        $where = array(
            'electrician_id'=>array('eq',0),
            'is_install'=>1,    //需要安装的
            'order_status' => array(
                'gt',0
            ),//订单状态为支付完成后的
            'install_type'=>'1',//安装类型为系统抢单
        );

        $row = 10;
        $p = $_GET['p'] ? $_GET['p'] : 1;
        $count =  M('order o')
            ->field('o.*,ua.*,pr.name AS province,ci.name AS city,co.name AS county,tw.name AS town')
            ->join('JOIN __USER_ADDRESS__ AS ua ON o.address_id = ua.address_id')
            ->join('JOIN __AREA__ pr ON pr.code = ua.province')
            ->join('JOIN __AREA__ ci ON ci.code = ua.city')
            ->join('JOIN __AREA__ co ON co.code = ua.county')
            ->join('JOIN __AREA__ tw ON tw.code = ua.town')
            ->where($where)
            ->count("distinct order_number");
        $Page = new \Think\Page($count,$row);
        $show = $Page->show();
        //获取该用户的全部订单
        $order_list =  M('order o')
            ->field('o.*,ua.*,pr.name AS province,ci.name AS city,co.name AS county,tw.name AS town')
            ->join('JOIN __USER_ADDRESS__ AS ua ON o.address_id = ua.address_id')
            ->join('JOIN __AREA__ pr ON pr.code = ua.province')
            ->join('JOIN __AREA__ ci ON ci.code = ua.city')
            ->join('JOIN __AREA__ co ON co.code = ua.county')
            ->join('JOIN __AREA__ tw ON tw.code = ua.town')
            ->where($where)
            ->group('order_number')
            ->order('pay_time asc')
            ->page($p,$row)
            ->select();

        //遍历计算总安装费
        foreach($order_list AS $k => $v){
            $total_install_price = '';//总安装费
            $goods_order = M('order')->where(array('order_number'=>$v['order_number']))->select();
            foreach($goods_order AS $key => $val){
                $total_install_price += $val['install_price'];
            }
            $order_list[$k]['total_install_price'] =  $total_install_price;
        }
        
        $shop_qiang = 'jumpPage';
        $this->assign('shop_qiang',$shop_qiang);
        $this->assign('order_list',$order_list);
        $this->assign('page',$show);
        $this->assign('cate_name',$cate_name);
        $this->display();
    }

    //已抢订单
    public function shop_install_order(){
        //获取一级分类
        $cate_name = M('good_cate')->field('id,good_cate_name')->where('good_parent_id=0 OR good_parent_id=id')->select();
        //将二级分类插入到一级中
        foreach ($cate_name as $k=>$v){
            $cate_name[$k]['data'] = M('good_cate')->field('id,good_cate_name')->where('good_parent_id!=id and good_parent_id='.$v['id'])->select();
        }

        $where = array(
            'electrician_id'=>session('user_id'),
            'is_install'=>1,    //需要安装的
            'install_type'=>'1',//安装类型为系统抢单
        );

        $row = 10;
        $p = $_GET['p'] ? $_GET['p'] : 1;
        $count =  M('order o')
            ->field('o.*,ua.*,pr.name AS province,ci.name AS city,co.name AS county,tw.name AS town')
            ->join('JOIN __USER_ADDRESS__ AS ua ON o.address_id = ua.address_id')
            ->join('JOIN __AREA__ pr ON pr.code = ua.province')
            ->join('JOIN __AREA__ ci ON ci.code = ua.city')
            ->join('JOIN __AREA__ co ON co.code = ua.county')
            ->join('JOIN __AREA__ tw ON tw.code = ua.town')
            ->where($where)
            ->count("distinct order_number");
        $Page = new \Think\Page($count,$row);
        $show = $Page->show();
        //获取该用户的全部订单
        $order_list =  M('order o')
            ->field('o.*,ua.*,pr.name AS province,ci.name AS city,co.name AS county,tw.name AS town')
            ->join('JOIN __USER_ADDRESS__ AS ua ON o.address_id = ua.address_id')
            ->join('JOIN __AREA__ pr ON pr.code = ua.province')
            ->join('JOIN __AREA__ ci ON ci.code = ua.city')
            ->join('JOIN __AREA__ co ON co.code = ua.county')
            ->join('JOIN __AREA__ tw ON tw.code = ua.town')
            ->where($where)
            ->group('order_number')
            ->order('pay_time asc')
            ->page($p,$row)
            ->select();

        //遍历计算总安装费
        foreach($order_list AS $k => $v){
            $total_install_price = '';//总安装费
            $goods_order = M('order')->where(array('order_number'=>$v['order_number']))->select();
            foreach($goods_order AS $key => $val){
                $total_install_price += $val['install_price'];
            }
            $order_list[$k]['total_install_price'] =  $total_install_price;
        }
        $this->assign('order_list',$order_list);
        $this->assign('page',$show);
        $this->assign('cate_name',$cate_name);
        $this->display();
    }

    //指派订单
    public function shop_send_order(){
        //获取一级分类
        $cate_name = M('good_cate')->field('id,good_cate_name')->where('good_parent_id=0 OR good_parent_id=id')->select();
        //将二级分类插入到一级中
        foreach ($cate_name as $k=>$v){
            $cate_name[$k]['data'] = M('good_cate')->field('id,good_cate_name')->where('good_parent_id!=id and good_parent_id='.$v['id'])->select();
        }

        //将电工未同意的就近安装过期订单改为默认抢单
        $time = strtotime("-24 hours");
        $back_time =  date("Y-m-d H:i:s",$time);
        $condition = array(
            'install_type'=>2,
            'electrician_id'=>session('user_id'),
            'electrician_confirm'=>array(
                'neq',1
            ),
            'pay_time'=>array(
                'lt',$back_time
            )
        );
        $data['install_type'] = 1;
        $data['electrician_confirm'] = '';
        $data['electrician_id'] = 0;
        M('order')->where($condition)->save($data);

        $where = array(
            'electrician_id'=>session('user_id'),
            'is_install'=>1,    //需要安装的
            'install_type'=>'2',//安装类型为指派订单
            'order_status'=>array(
                'gt',0
            ),
        );

        $row = 10;
        $p = $_GET['p'] ? $_GET['p'] : 1;
        $count =  M('order o')
            ->field('o.*,ua.*,cp.count_price,pr.name AS province,ci.name AS city,co.name AS county,tw.name AS town')
            ->join('JOIN __USER_ADDRESS__ AS ua ON o.address_id = ua.address_id')
            ->join('JOIN __COUNT_PRICE__ cp ON cp.order_number = o.order_number')
            ->join('JOIN __AREA__ pr ON pr.code = ua.province')
            ->join('JOIN __AREA__ ci ON ci.code = ua.city')
            ->join('JOIN __AREA__ co ON co.code = ua.county')
            ->join('JOIN __AREA__ tw ON tw.code = ua.town')
            ->where($where)
            ->count("distinct o.order_number");
        $Page = new \Think\Page($count,$row);
        $show = $Page->show();
        //获取该用户的全部订单
        $order_list =  M('order o')
            ->field('o.*,ua.*,cp.count_price,pr.name AS province,ci.name AS city,co.name AS county,tw.name AS town')
            ->join('JOIN __USER_ADDRESS__ AS ua ON o.address_id = ua.address_id')
            ->join('JOIN __COUNT_PRICE__ cp ON cp.order_number = o.order_number')
            ->join('JOIN __AREA__ pr ON pr.code = ua.province')
            ->join('JOIN __AREA__ ci ON ci.code = ua.city')
            ->join('JOIN __AREA__ co ON co.code = ua.county')
            ->join('JOIN __AREA__ tw ON tw.code = ua.town')
            ->where($where)
            ->group('o.order_number')
            ->order('pay_time asc')
            ->page($p,$row)
            ->select();

        //遍历计算总安装费
        foreach($order_list AS $k => $v){
            $total_install_price = '';//总安装费
            $goods_order = M('order')->where(array('order_number'=>$v['order_number']))->select();
            foreach($goods_order AS $key => $val){
                $total_install_price += $val['install_price'];
            }
            $order_list[$k]['total_install_price'] =  $total_install_price;
        }
        $this->assign('order_list',$order_list);
        $this->assign('page',$show);
        $this->assign('cate_name',$cate_name);
        $this->display();
    }

    //尾款订单
    public function final_payment_order(){
        //获取一级分类
        $cate_name = M('good_cate')->field('id,good_cate_name')->where('good_parent_id=0 OR good_parent_id=id')->select();
        //将二级分类插入到一级中
        foreach ($cate_name as $k=>$v){
            $cate_name[$k]['data'] = M('good_cate')->field('id,good_cate_name')->where('good_parent_id!=id and good_parent_id='.$v['id'])->select();
        }

        $time = strtotime("-1 year");
        $back_time =  date("Y-m-d 23:59:59",$time);
        $where = array(
            'electrician_id'=>session('user_id'),
            'install_status'=>1,
            'install_time'=>array(
                'elt',$back_time
            )
        );

        $row = 10;
        $p = $_GET['p'] ? $_GET['p'] : 1;
        $count =  M('order o')
            ->field('o.*,ua.*,cp.count_price,pr.name AS province,ci.name AS city,co.name AS county,tw.name AS town')
            ->join('JOIN __USER_ADDRESS__ AS ua ON o.address_id = ua.address_id')
            ->join('JOIN __COUNT_PRICE__ cp ON cp.order_number = o.order_number')
            ->join('JOIN __AREA__ pr ON pr.code = ua.province')
            ->join('JOIN __AREA__ ci ON ci.code = ua.city')
            ->join('JOIN __AREA__ co ON co.code = ua.county')
            ->join('JOIN __AREA__ tw ON tw.code = ua.town')
            ->where($where)
            ->count("distinct o.order_number");
        $Page = new \Think\Page($count,$row);
        $show = $Page->show();
        //获取该用户的全部订单
        $order_list =  M('order o')
            ->field('o.*,ua.*,cp.count_price,pr.name AS province,ci.name AS city,co.name AS county,tw.name AS town')
            ->join('JOIN __USER_ADDRESS__ AS ua ON o.address_id = ua.address_id')
            ->join('JOIN __COUNT_PRICE__ cp ON cp.order_number = o.order_number')
            ->join('JOIN __AREA__ pr ON pr.code = ua.province')
            ->join('JOIN __AREA__ ci ON ci.code = ua.city')
            ->join('JOIN __AREA__ co ON co.code = ua.county')
            ->join('JOIN __AREA__ tw ON tw.code = ua.town')
            ->where($where)
            ->group('o.order_number')
            ->order('final_payment_status asc,pay_time asc')
            ->page($p,$row)
            ->select();
        //遍历计算总安装费
        foreach($order_list AS $k => $v){
            $total_install_price = '';//总安装费
            $goods_order = M('order')->where(array('order_number'=>$v['order_number']))->select();
            foreach($goods_order AS $key => $val){
                $total_install_price += $val['install_price'];
            }
            $order_list[$k]['total_install_price'] =  $total_install_price;
        }
        $this->assign('order_list',$order_list);
        $this->assign('page',$show);
        $this->assign('cate_name',$cate_name);
        $this->display();
    }

    //电工确认操作
    public function electrician_confirm(){
        $where = array(
            'order_number'=>I('order_number')
        );
        $data['electrician_confirm'] = I('electrician_confirm');   //安装完成
        $data['electrician_confirm_time'] = date('Y-m-d H:i:s');   //完成时间
        $data['final_payment_status'] = 1;   //尾款状态：待处理
        if(false === M('order')->where($where)->save($data)){
            echo -1;
        }else{
            echo 1;
        }
    }
    
    //订单弹窗列表
    public function order_list(){
        $where = array(
            'order_number'=>I('order_number')
        );
        $list = M('order')->field('good_picture,good_name,grade,num,order_status')->where($where)->select();
        foreach($list AS $k => $v){
            switch($v['order_status']){
                case -2:
                    $list[$k]['order_status'] = '已删除';
                    break;
                case 1:
                    $list[$k]['order_status'] = '待发货';
                    break;
                case 2:
                    $list[$k]['order_status'] = '待收货';
                    break;
                case 3:
                    $list[$k]['order_status'] = '已收货';
                    break;
                case 4:
                    $list[$k]['order_status'] = '申请换货';
                    break;
                case 5:
                    $list[$k]['order_status'] = '确认换货';
                    break;
                case 6:
                    $list[$k]['order_status'] = '已换货';
                    break;
            }
        }
        echo json_encode($list);
    }

    //抢单操作
    public function qiang_action(){
        $where = array(
            'order_number'=>I('order_number')
        );
        $data['electrician_id'] = session('user_id');
        $data['grab_time'] = date('Y-m-d H:i:s');
        $model = new Model();
        $model->startTrans();
        //判断订单状态，是否已经被抢
        $map = array(
            'order_number'=>I('order_number'),
            'electrician_id'=>array('eq',0)
        );
        if(!M('order')->where($map)->select()){
            echo -2;  //订单已被抢
        }else{
            if(false === M('order')->where($where)->save($data)){
                $model->rollback();
                echo -1;//数据异常
            }else{
                echo 1;//抢单成功
            }
        }
        $model->commit();
    }

    //订单安装完成操作
    public function install_succ(){
        $where = array(
            'order_number'=>I('order_number')
        );
        $data['install_status'] = 1;   //安装完成
        $data['install_time'] = date('Y-m-d H:i:s');   //安装完成
        if(false === M('order')->where($where)->save($data)){
            echo -1;
        }else{
            echo 1;
        }
    }

    //加盟店
    public function shop_join_store(){
        //获取所有省份
        $province_list = M('region')->where(array('pid' => 1))->select();

        $this->assign('province_list',$province_list);
        $this->display();
    }

    //AJAX -- 通过选择加盟店所在城市，获取该城市所有的加盟店
    public function dealer_list()
    {
        $dealer_list = M('dealer')->field('id,store_name')->where(array('city' => I('city')))->select();
        echo json_encode($dealer_list);
    }

    //加盟店详情
    public function shop_pavilion(){
        //获取所有省份
        $pavilionInfo = M('dealer as d')
                    ->field('d.*,u.phone,pr.name AS province,ci.name AS city,co.name AS county')
                    ->join('JOIN __USER__ u ON u.id = d.dealer_id')
                    ->join('JOIN __REGION__ pr ON pr.id = d.province')
                    ->join('JOIN __REGION__ ci ON ci.id = d.city')
                    ->join('JOIN __REGION__ co ON co.id = d.county')
                    ->where(array('d.id' => I('id')))
                    ->find();

        $this->assign('pavilionInfo',$pavilionInfo);
        $this->display();
    }

    //申请加盟
    public function apply_join(){
        if($_FILES){
            $picture = uploadPicture();
            if($picture){
                $data['store_picture'] = $picture;
            }
        }
        $data['user_name'] = I('user_name');
        $data['phone'] = I('phone');
        $data['address_detailed'] = I('address_detailed');
        $data['real_store'] = I('real_store');
        $data['store_area'] = I('store_area');
        $data['add_time'] = date('Y-m-d H:i:s');
        if(M('apply_join')->add($data)){
            $this->success('提交成功');
        }else{
            $this->error('提交失败');
        }
    }

    /**
     * 发送手机短信验证码
     */
    public function sendCode()
    {
        $telephone = I('phone');
        $type = I('type');
        if(!checkTelFormat($telephone)){
            echo -1;//手机格式错误
            exit;
        }
        //如果是忘记密码，判断该手机号是否存在
        if($type == 'zhaohui'){
            if(!M('user')->where(array('phone'=>$telephone))->getField('id')){
                echo -2;//该用户不存在
                exit;
            }
        }

        $code = rand(100000, 999999) . '';//转化成字符串格式
        //将生成的验证码存入数据库
        $mes['code'] = $code;
        $mes['telephone'] = $telephone;
        $mes['sendtime'] = date("Y-m-d H:i:s");
        //将验证码存到数据库
        M('verify')->add($mes);
        $data = array('code' => $code);
        $tpl = "SMS_109545252";
        $mess = sendSms($telephone, $tpl, $data);
        $res = $mess->Code;
        if($res == 'OK'){
            echo 1;//成功
        }else{
            echo 0;//失败
        }
    }
}